package com.usermanage.controller;

import com.ordercore.Common.OrderIOC;
import com.ordercore.Util.ResponseData.ResponseData;
import com.ordercore.Util.Verify.pzDataVerifyUtil;
import com.usermanage.SecurityConfig.SpringSecurityUtils;
import com.usermanage.SecurityConfig.UserDetail;
import com.usermanage.Service.*;
import com.usermanage.ServiceImpl.MessageServiceImpl;
import com.usermanage.beanParam.*;
import com.usermanage.util.*;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;

/**
 * 前台选装
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Resource
    private OrderService orderService;

    @Resource
    private UserService userService;

    @Resource
    private CompanyService companyService;

    @Resource
    private ContractService contractService;

    @Resource
    private MessageServiceImpl messageService;

    @Resource
    private LogisticsService logisticsService;

    @Resource
    private ContractRealTimePriceService contractRealTimePriceService;

    @Resource
    private PMOrderService pmOrderService;

    @Resource
    private ProjectService projectService;

    @Resource
    private SequenceService sequenceService;

    /**
     * 获取订单筛选条件--项目列表
     *
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping("/projectList.json")
    public JsonData projectList() {
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        if (userDetail == null) {
            return JsonData.fail("请登录");
        }
        List<Map> projectListAll = new ArrayList<>();
        //品宅方登录获取所有项目列表
        if ("1".equals(userDetail.getCompany_id())) {
            projectListAll.addAll(pmOrderService.ProjectListByPM());
            projectListAll.addAll(projectService.projectListByCompany(userDetail.getCompany_id()));
            //集栋用户获取集栋项目列表
        } else if ("20".equals(userDetail.getCompany_id())) {
            projectListAll = pmOrderService.ProjectListByPM();
            //其余用户获取签订项目列表
        } else {
            projectListAll = projectService.projectListByCompany(userDetail.getCompany_id());
        }
        return JsonData.success(projectListAll);
    }

    /**
     * 根据物流单号查询物流信息
     *
     * @param no
     * @return
     * @throws Exception
     */
    @RequestMapping("/logistics.json")
    public JsonData expressInformation(String no) throws Exception {
        String result = logisticsService.getOrderTracesByJson(no);
        Map map = StringUtil.JsonToMap(result);
        List<Map> list = StringUtil.JsonToList(StringUtil.ObjectToJson(map.get("Shippers")));
        return JsonData.success(list.get(0).get("ShipperCode").toString());
    }

    /**
     * 保存订单
     *
     * @param addreessBean
     * @param bindingResult
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/save.json", method = RequestMethod.POST)
    public JsonData saveOrder(@Valid AddreessBean addreessBean, BindingResult bindingResult) throws Exception {
        // 验证提交数据是否合法
        if (bindingResult.hasErrors()) {
            return JsonData.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        // addressBean为用户收货地址信息
        // 以下为用户购物车信息，提交推送给订单系统
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        // 验证合同
        ContractBean checkBean = new ContractBean();
        OrderBean bean = new OrderBean();
        // 当前登陆用户企业信息
        Optional<CompanyBean> optional;
        checkBean.setContract_states("11");
        {
            checkBean.setCompanyB_id(userDetail.getCompany_id());
            bean.setUser_id(String.valueOf(userDetail.getId()));
            optional = companyService.findById(Integer.valueOf(userDetail.getCompany_id()));
            addreessBean.setConsignee_name(userDetail.getUsername());
        }
        // 获取购物车所有信息
        bean.setUser_id(userDetail.getId().toString());
        List<OrderBean> list = orderService.findAll(bean);
        if (list.size() <= 0) {
            return JsonData.fail("订单不能为空。");
        }
        List<Map> listMap = new ArrayList<>();
        for (OrderBean resultBean : list) {
            Map map = StringUtil.JsonToMap(resultBean.getOrder_sku());
            listMap.add(map);
        }
        if (StringUtils.isBlank(addreessBean.getConsignee_address())) {
            addreessBean.setConsignee_address("");
        }
        if (StringUtils.isBlank(addreessBean.getConsignee_information())) {
            addreessBean.setConsignee_information("");
        }
        if (StringUtils.isBlank(addreessBean.getBuyer())) {
            addreessBean.setBuyer("");
        }
        if (StringUtils.isBlank(addreessBean.getRemark())) {
            addreessBean.setRemark("");
        }
        // 合同甲方企业信息
        Optional<CompanyBean> optionalA = companyService.findById(1);
        addreessBean.setType("analog");
        addreessBean.setOrder_source("eos");
        addreessBean.setPartyA_id(String.valueOf(optionalA.get().getId()));
        addreessBean.setPartyA_name(optionalA.get().getCompany_name());
        addreessBean.setCrtTime(DateUtil.getNowTime("yyyy-MM-dd"));
        addreessBean.setContext(StringUtil.ObjectToJson(listMap));
        addreessBean.setUserGroup_id(optional.get().getId());
        addreessBean.setUserGroup_name(optional.get().getCompany_name());
        String num = sequenceService.getSequenceNum("order");
        String orderBillId = "EOS-" + DateUtil.getNowTime("yyyyMMdd") + "-" + StringUtil.getCode(num, 5);
        addreessBean.setOrderBill_id(orderBillId);
        addreessBean.setId(0);// 默认0，方便熊数据解析，没有实际用途
        addreessBean.setDiscount("0");// 优惠金额默认为0
        addreessBean.setTransport_price("0");// 运费默认为0
        String param = StringUtil.ObjectToJson(addreessBean);
        try {
            com.ordercore.Bean.OrderBean orderBean = OrderIOC.baseAnalysisBill(param);
            String message_body = addreessBean.getUserGroup_name() + "  " + userDetail.getUsername() + "  于  " + DateUtil.getNowDayString() + "  下了一笔采购订单，编号为：  " + orderBillId + "  请确认清单。";
            String message_creater = bean.getUser_id();
            log.info("下单成功，进入推送消息接口");
            orderCreateMessage(message_body, message_creater, orderBillId, String.valueOf(orderBean.getOrderBean_pk()));
            for (OrderBean resultBean : list) {
                orderService.delete(resultBean);
            }
            return JsonData.success();
        } catch (Exception e) {
            return JsonData.fail("下单失败，请重试！");
        }

    }

    /**
     * 订单列表页
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/orderList.page", method = RequestMethod.GET)
    public ModelAndView orderListPage() throws Exception {
        ModelAndView mv = new ModelAndView();
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        if ("99".equals(userDetail.getCompany_type())) {
            mv.setViewName("/shopping/adminOrderList");
        } else {
            String company_id = userDetail.getCompany_id();
            if (company_id.equals(StaticUtil.JDCOMPANY)) {
                mv.addObject("bool", false);
            } else {
                mv.addObject("bool", true);
            }
            mv.setViewName("/shopping/orderList");
        }
        if (userDetail.getId() == 1) {
            mv.addObject("admin", true);
        } else {
            mv.addObject("admin", false);
        }
        return mv;
    }

    /**
     * 订单数据列表，接口拉取数据
     *
     * @param orderNo      订单编号
     * @param userName     用户名
     * @param startTime    开始时间
     * @param endTime      结束时间
     * @param sales_status 订单状态
     * @param page         页码
     * @param limit        每页数量
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/orderList.json", method = RequestMethod.POST)
    public JsonData orderList(String orderNo, String userName, String startTime, String endTime, String sales_status,
                              String page, String limit, String buyer) throws Exception {
        if (StringUtils.isBlank(page)) {
            page = StaticUtil.pageIndex;
        }
        if (StringUtils.isBlank(limit)) {
            limit = StaticUtil.sizeCount;
        }
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
//        String user_id = String.valueOf(userDetail.getId());
        Map map = new HashMap();
        if ("1".equals(userDetail.getCompany_id())) {// 甲方获取所有列表
            map.put("partyA_id", userDetail.getCompany_id());
        } else {
            map.put("userGroup_id", userDetail.getCompany_id());
        }
        Integer user_id = null;
        if (StringUtils.isNotBlank(userName)) {
            List<UserBean> userList = userService.findAllUserByUserName(userName);
            if (userList.size() > 0) {
                user_id = userList.get(0).getId();
            }
        }
        map.put("order_id", orderNo);
        map.put("user_id", user_id);
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        map.put("customStat", sales_status);
        map.put("type", "25");
        map.put("page", page);
        map.put("limit", limit);
        String param = StringUtil.ObjectToJson(map);
        ResponseData result = OrderIOC.queryOrderSummary(param);//返回的就是JSONDATA
        List<Map> list = null;
        int count = 0;
        // #1000 下单初始化
        // #1001 供方确认
        // #1002 需方确认
        // #1003 作废
        if (result.isRet()) {
            String str = StringUtil.ObjectToJson(result.getData());
            list = StringUtil.JsonToList(str);
            for (Map resultMap : list) {
                if (!"null".equals(String.valueOf(resultMap.get("user_id")))) {
                    UserBean bean = userService.findById(Integer.valueOf(resultMap.get("user_id").toString())).get();
                    resultMap.put("user_name", bean.getUser_name());
                    resultMap.put("user_dept", bean.getUser_dept());
                } else {
                    resultMap.put("user_name", "");
                    resultMap.put("user_dept", "");
                }
                CompanyBean companyBean = companyService.findById(Integer.valueOf(userDetail.getCompany_id())).get();
                resultMap.put("company_name", companyBean.getCompany_name());

            }
            count = result.getCount();
        }
        Map resultMap = new HashMap();
        resultMap.put("list", list);
        resultMap.put("total", count == 0 ? 1 : count);
        return JsonData.success(resultMap);
    }

//    @RequestMapping("/getSkuListByUserId.json")
//    public JsonData skuList(String user_id) throws Exception {
//        UserBean userBean = userService.findUserDetail(user_id);
//        ContractBean checkBean = new ContractBean();
//        checkBean.setContract_states("11");
//        checkBean.setCompanyB_id(userBean.getCompany_id());
//        checkBean.setContract_type("ration");
//        List<ContractBean> contractList = contractService.findAll(checkBean);
//        if (contractList.size() == 0) {
//
//        }
//        ContractBean contractBean = contractList.get(0);
//        String contractSku = contractBean.getContract_sku();
//        JSONArray json = JSONArray.fromObject(StringUtil.JsonToMap(contractSku).get("sku"));
//        List<Map> skuList = new ArrayList<>();
//        for (int i = 0; i < json.size(); i++) {
//            Map map = StringUtil.JsonToMap(json.getString(i));
//            map.put("purNum", "1");
//            map.put("arriveTime", DateUtil.getNowTime("yyyy-MM-dd"));
//            skuList.add(map);
//        }
//        return JsonData.success(skuList);
//    }

    @RequestMapping(value = "/reimport.json", method = RequestMethod.POST)
    public JsonData reimport(String orderNo, String orderBean_pk) throws Exception {
        Map map1 = new HashMap<>();
        map1.put("order_id", orderNo);
        map1.put("orderBean_pk", orderBean_pk);
        map1.put("type", "25");
        try {
            Map result = OrderIOC.queryDeteilById(StringUtil.ObjectToJson(map1));
            if (pzDataVerifyUtil.isEmptyMap(result)) {
                return JsonData.fail();
            }
            messageService.rabbitMq("kingDeeOrderChange", "kingDeeOrderKey", StringUtil.ObjectToJson(result));
            return JsonData.success();
        } catch (Exception e) {
            return JsonData.fail();
        }
    }


    /**
     * 确认或者删除订单
     *
     * @param orderNo 订单编号
     * @param type    类型（del：代表删除，affirm：代表确认）
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/operate.json", method = RequestMethod.POST)
    public JsonData operateOrdre(String orderNo, String type, String code, String orderBean_pk, String admin, String userGroup_name) throws Exception {
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        Map map = new HashMap();
        map.put("orderBill_id", orderNo);
        map.put("orderBean_pk", orderBean_pk);
        map.put("orderBill_flow", 25);

        if ("del".equals(type)) {
            map.put("orderBill_customStat", code);
        } else if ("affirm".equals(type)) {
            if ("true".equals(admin)) {
                map.put("supply_userId", userDetail.getId());
            }
            map.put("orderBill_customStat", code);
        } else if ("finish".equals(type)) {
            map.put("orderBill_customStat", code);
        } else {
            return JsonData.fail("系统异常！");
        }
        String param = StringUtil.ObjectToJson(map);
        try {
            com.ordercore.Bean.OrderBean orderBean = OrderIOC.updateOrder(param);
            if ("del".equals(type)) {
                //删除订单不推送
            } else {
                MessageBean messageBean = new MessageBean();
                messageBean.setMessage_status("99");
                messageBean.setMessage_type("msg001");
                messageBean.setMessage_creater(SpringSecurityUtils.getCurrentUser().getId().toString());
                messageBean.setMessage_no(orderNo);
                messageBean.setMessage_url("/order/orderDetail.page?orderNo=" + orderNo + "&orderBean_pk=" + orderBean_pk);
                if ("true".equals(admin)) {
                    String messageBody = "上海品宅装饰科技有限公司的  " + userDetail.getUsername() + "  于  " + DateUtil.getNowDayString() + "  确认了销售订单，编号为： " + orderNo + "  请确认订单是否有误。";
                    messageBean.setMessage_body(messageBody);
                    messageBean.setMessage_sendee(orderBean.getUser_id());
                } else {
                    String messageBody = orderBean.getUserGroup_name() + "  " + userDetail.getUsername() + "  于  " + DateUtil.getNowDayString() + "  确认了采购订单，编号为： " + orderNo + "  请及时查看并安排出库。";
                    messageBean.setMessage_body(messageBody);
                    messageBean.setMessage_sendee(orderBean.getSupply_userId());
                    Map map1 = new HashMap<>();
                    map1.put("order_id", orderNo);
                    map1.put("orderBean_pk", orderBean_pk);
                    map1.put("type", "25");
                    Map result = OrderIOC.queryDeteilById(StringUtil.ObjectToJson(map1));
                    messageService.rabbitMq("kingDeeOrderChange", "kingDeeOrderKey", StringUtil.ObjectToJson(result));
                }
                messageService.send(messageBean);
            }
            return JsonData.success();
        } catch (Exception e) {
            return JsonData.fail("系统异常");
        }

    }

    /**
     * 订单列表页
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/orderDetail.page", method = RequestMethod.GET)
    public ModelAndView orderDetail(String orderNo, String orderBean_pk) throws Exception {
        ModelAndView mv = new ModelAndView();
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        if ("99".equals(userDetail.getCompany_type())) {
            mv.addObject("success", "success");
//            mv.addObject("url", StaticUtil.ORDERIP);
//            mv.addObject("NSLUrl", StaticUtil.SKUIP);
            mv.setViewName("/shopping/adminDetail");
        } else {
            mv.addObject("success", "fail");
            mv.setViewName("/shopping/detail");
        }
        // mv.setViewName("/shopping/detail");
        mv.addObject("orderNo", orderNo);
        mv.addObject("orderBean_pk", orderBean_pk);
        return mv;
    }

    /**
     * 获取订单详情
     *
     * @param orderNo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/orderDetail.json", method = RequestMethod.POST)
    public String orderJson(String orderNo, String orderBean_pk) throws Exception {
        Map map = new HashMap();
        map.put("order_id", orderNo);
        map.put("orderBean_pk", orderBean_pk);
        map.put("type", "25");
        String param = StringUtil.ObjectToJson(map);
        try {
            Map<String, Object> result = OrderIOC.queryDeteilById(param);
            return StringUtil.ObjectToJson(JsonData.success(result));
        } catch (Exception e) {
            return String.valueOf(JsonData.fail("获取订单详情失败，请稍后重试"));
        }
    }

    /**
     * 修改订单信息（运费）
     *
     * @param orderNo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updateOrder.json", method = RequestMethod.POST)
    public JsonData updateOrder(String orderNo, String price, String transport_price, String discount, String orderBean_pk, String userGroup_name, String user_name)
            throws Exception {
        Map map = new HashMap();
        map.put("orderBill_id", orderNo);
        map.put("orderBean_pk", orderBean_pk);
        map.put("orderBill_flow", "25");
        map.put("price", price);
        map.put("transport_price", transport_price);
        map.put("discount", discount);
        String param = StringUtil.ObjectToJson(map);
        try {
            com.ordercore.Bean.OrderBean orderBean = OrderIOC.updateOrder(param);
            return JsonData.success();
        } catch (Exception e) {
            return JsonData.fail("修改订单信息失败，请稍后重试！");
        }
    }

    /**
     * 上传付款凭证
     *
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/file.json", method = RequestMethod.POST)
    public String upload(MultipartFile file) throws Exception {
        String url = OssUtil.upload(file);
        return url;
    }

    /**
     * 删除付款凭证
     *
     * @param path
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/delFile.json", method = RequestMethod.POST)
    public JsonData delUpload(String path) throws Exception {
        OssUtil.deletePic(path);
        return JsonData.success();
    }

    /**
     * 付款接口
     *
     * @param path
     * @param price
     * @param orderNo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/payment.json", method = RequestMethod.POST)
    public JsonData payment(String path, String price, String orderNo, String orderBean_pk) throws Exception {
        if (StringUtils.isBlank(path)) {
            return JsonData.fail("付款凭证上传异常！");
        }
        if (StringUtils.isBlank(price)) {
            return JsonData.fail("价格不能为空！");
        }
        if (StringUtils.isBlank(orderNo)) {
            return JsonData.fail("订单编号不能为空！");
        }
        String url = StaticUtil.OSSURL + path;
        Map map = new HashMap();
        map.put("orderBill_id", orderNo);// 订单id
        map.put("orderBean_pk", orderBean_pk);// 订单id
        map.put("payAmout", price);// 付款金额
        map.put("payVoucher", url);// 付款凭证url
        map.put("payTime", DateUtil.getNowTime("yyyyMMdd"));
        map.put("payStat", "01");
        String param = StringUtil.ObjectToJson(map);
        OrderIOC.paymentBillAdd(param);
        return JsonData.success();
    }

    // ***************************************************************收货单发货单部分********************************************************************

    /**
     * 发货单页
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/dispatch.page", method = RequestMethod.GET)
    public ModelAndView dispatchPage() throws Exception {
        ModelAndView mv = new ModelAndView();
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        if ("99".equals(userDetail.getCompany_type())) {
            mv.addObject("success", "fail");
        } else {
            mv.addObject("success", "success");
        }
        mv.addObject("url", StaticUtil.OUTSTOCK);
        mv.setViewName("/dispatch/dispatchList");
        return mv;
    }

    /**
     * 收货单界面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/consignee.page", method = RequestMethod.GET)
    public ModelAndView consigneeListPage() throws Exception {
        ModelAndView mv = new ModelAndView();
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        if ("1".equals(userDetail.getCompany_id())) {
            mv.addObject("success", "success");
        } else {
            mv.addObject("success", "fail");
        }
        mv.setViewName("/consignee/consigneeList");
        return mv;
    }

    /**
     * 发货单列表
     *
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/billsList.json", method = RequestMethod.POST)
    public JsonData billsListJson(String orderNo, String userName, String startTime, String endTime, String project_name, String page, String limit,
                                  String type) throws Exception {
        if (StringUtils.isBlank(page)) {
            page = StaticUtil.pageIndex;
        }
        if (StringUtils.isBlank(limit)) {
            limit = StaticUtil.sizeCount;
        }
        if (StringUtils.isBlank(type)) {
            return JsonData.fail();
        }
        // 获取用户信息
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        String user_id = String.valueOf(userDetail.getId());
        Map map = new HashMap();
        if ("1".equals(userDetail.getCompany_id())) {// 总公司获取用户订单信息
        } else {// 合作商获取自己订单
            map.put("userGroup_id", userDetail.getCompany_id());
            if (type.equals("20")) {
                map.put("customStat", "1007");
            } else if (type.equals("23")) {
            }
        }
        // 接口调用
        map.put("supply_user", userName);
        map.put("order_id", orderNo);
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        map.put("project_name", project_name);
        map.put("type", type);
        map.put("page", page);
        map.put("limit", limit);
        String param = StringUtil.ObjectToJson(map);
        ResponseData responseData = OrderIOC.queryOrderSummary(param);
        List<Map> list = null;
        int count = 0;
        if (responseData.isRet()) {
            String str = StringUtil.ObjectToJson(responseData.getData());
            list = StringUtil.JsonToList(str);
            if ("20".equals(type)) {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).get("orderBill_customStat").toString().equals("1007") || list.get(i).get("orderBill_customStat").toString().equals("1006")) {
                        list.get(i).put("user_id", userIdToUserName(list.get(i).get("user_id").toString()));
                    } else {
                        list.get(i).put("user_id", "");
                    }
                }
            }
            count = responseData.getCount();
        } else {
            FileUtil.writeLinesByLog("OrderController中dispatchListJson方法异常，接口返回数据" + responseData + "type为" + type);
        }
        Map resultMap = new HashMap();
        resultMap.put("list", list);
        resultMap.put("page", page);
        resultMap.put("total", count);
        resultMap.put("orderNo", orderNo);
        resultMap.put("userName", userName);
        resultMap.put("startTime", startTime);
        resultMap.put("size", limit);
        return JsonData.success(resultMap);
    }

    /**
     * 收货单详情界面
     *
     * @param orderNo
     * @param type    type = detail表示定位到收货单详情界面，type = affirm 表示收货单确认界面
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/billPage.page", method = RequestMethod.GET)
    public ModelAndView affirmDispatchPage(String orderNo, String type, String orderBean_pk, String customStat) throws Exception {
        ModelAndView mv = new ModelAndView();
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        if ("99".equals(userDetail.getCompany_type())) {
            if (customStat.equals("1000")) {
                mv.addObject("success", "success");
            } else {
                mv.addObject("success", "fail");
            }
        } else {
            mv.addObject("success", "fail");
        }
        mv.addObject("orderNo", orderNo);
        mv.addObject("orderBean_pk", orderBean_pk);

        // 根据type判断界面
        if ("detail".equals(type)) {
            mv.setViewName("/dispatch/dispatchDetail");
        } else if ("affirm".equals(type)) {
            mv.addObject("crtTime", DateUtil.getNowDayString());
            mv.setViewName("/dispatch/affirmDispatch");
        } else if ("consignee".equals(type)) {
            mv.setViewName("/consignee/consigneeDetail");
        } else if ("edit".equals(type)) {
            mv.addObject("url", StaticUtil.ORDERIP);
            mv.setViewName("/dispatch/addLogistics");
        }
        mv.addObject("consignee_name", userDetail.getUsername());
        mv.addObject("url", StaticUtil.ORDERIP);
        return mv;
    }

    /**
     *
     */
    @RequestMapping(value = "/updateDispatchOrder.json", method = RequestMethod.POST)
    public JsonData updateDispatchOrder(String orderBill_id, String orderBean_pk, String orderBill_flow, String user_id, String transport_billNo, String remark) throws Exception {
        Map map = new HashMap();
        map.put("orderBill_id", orderBill_id);
        map.put("orderBean_pk", orderBean_pk);
        map.put("orderBill_flow", orderBill_flow);
        map.put("user_id", user_id);
        map.put("transport_billNo", transport_billNo);
        map.put("remark", remark);
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        map.put("buyer", userDetail.getId());
        map.put("crtTime", DateUtil.getNowDayString());
        map.put("orderBill_customStat", "1007");
        String param = StringUtil.ObjectToJson(map);
        try {
            com.ordercore.Bean.OrderBean orderBean = OrderIOC.updateOrder(param);
            String value = user_id.substring(1, user_id.length() - 1);
            String[] sendeList = value.split(",");
            for (int i = 0; i < sendeList.length; i++) {
                MessageBean messageBean = new MessageBean();
                messageBean.setMessage_creater(SpringSecurityUtils.getCurrentUser().getId().toString());
                messageBean.setMessage_no(orderBill_id);
                messageBean.setMessage_url("/order/billPage.page?type=affirm&orderNo=" + orderBill_id + "&orderBean_pk=" + orderBean_pk);
                messageBean.setMessage_body("上海品宅装饰科技有限公司的  " + SpringSecurityUtils.getCurrentUser().getUsername() + "  完成了发货单号为  " + orderBill_id + "  发货单的出库，物流号为  " + transport_billNo + "  ，请及时跟踪。");
                messageBean.setMessage_sendee(sendeList[i]);
                messageBean.setMessage_status("99");
                messageBean.setMessage_type("msg005");
                messageService.send(messageBean);
            }
            return JsonData.success();
        } catch (Exception e) {
            return JsonData.fail();
        }
    }


    /**
     * 验收单数据详情
     *
     * @param orderNo
     * @return bills
     * @throws Exception
     */
    @RequestMapping(value = "/billDetail.json", method = RequestMethod.POST)
    public JsonData billDetailJson(String orderNo, String type, String orderBean_pk) throws Exception {
        if (StringUtils.isBlank(orderNo) && StringUtils.isBlank(type)) {
            return JsonData.fail();
        }
        Map map = new HashMap();
        map.put("type", type);
        map.put("order_id", orderNo);
        map.put("orderBean_pk", orderBean_pk);
        String param = StringUtil.ObjectToJson(map);
        try {
            Map<String, Object> result = OrderIOC.queryDeteilById(param);
            if (!"23".equals(type)) {
                result.put("user_id", userIdToUserName(result.get("user_id").toString()));
            }
            return JsonData.success(result);
        } catch (Exception e) {
            return JsonData.fail("获取验收单数据详情失败，请稍后重试");
        }
    }

    /**
     * 验收单据 2018.10.10毛汶鑫定，一个单据只能验收一次。
     *
     * @param formData
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updateDispatch.json", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public JsonData updateDispatch(String formData) throws Exception {
        log.info("updateDispatch接收到的参数：" + formData);
        // 转成熊能解析的json格式
        boolean result;
        String messageBody = "";
        MessageBean messageBean = new MessageBean();
        Map map = StringUtil.JsonToMap(formData);
        if ("consignee".equals(map.get("type"))) {
            map.put("delivery_time", DateUtil.getNowDayString());
            map.put("affirm", SpringSecurityUtils.getCurrentUser().getUsername());
            try {
                com.ordercore.Bean.OrderBean orderBean = OrderIOC.updateOrder(StringUtil.ObjectToJson(map));
                result = true;
                messageBean.setMessage_sendee(orderBean.getUser_id());
                messageBean.setMessage_type("msg006");
                messageBody = "编号为：  " + map.get("orderBill_id") + "  的收货单，供应商联系人  " + SpringSecurityUtils.getCurrentUser().getUsername() + "  已确认数量，请查看。";
            } catch (Exception e) {
                result = false;
                messageBean.setMessage_sendee("1");
            }

        } else {

            //收货完成
            Map paramMap = new HashMap();
            paramMap.put("type", "20");
            paramMap.put("order_id", map.get("orderBill_id"));
            paramMap.put("orderBean_pk", map.get("orderBean_pk"));
            String param = StringUtil.ObjectToJson(paramMap);
            try {
                Map<String, Object> resultDetail = OrderIOC.queryDeteilById(param);
                resultDetail.put("orderBill_customStat", "1006");
                OrderIOC.updateOrder(StringUtil.ObjectToJson(resultDetail));
            } catch (Exception e) {
                log.error("修改订单失败：" + e.toString());
                return JsonData.fail("请求失败，请稍后重试");
            }
            String num = sequenceService.getSequenceNum("consignee");
            String orderBillId = "SH-" + DateUtil.getNowTime("yyyyMMdd") + "-" + StringUtil.getCode(num, 5);
            map.put("orderBill_id", orderBillId);
            String skuStr = StringUtil.ObjectToJson(map.get("context"));
            List<Map> list = StringUtil.JsonToList(skuStr);
            map.put("context", StringUtil.ObjectToJson(list));
            map.put("user_id", SpringSecurityUtils.getCurrentUser().getId());
            map.put("consignee_name", SpringSecurityUtils.getCurrentUser().getUsername());
            map.put("affirm", "无");
            try {
                com.ordercore.Bean.OrderBean orderBean = OrderIOC.baseAnalysisBill(StringUtil.ObjectToJson(map));
                result = true;
            } catch (Exception e) {
                result = false;
            }
            messageBean.setMessage_sendee(String.valueOf(map.get("supply_userId")));
            messageBean.setMessage_type("msg006");
            messageBody = SpringSecurityUtils.getCurrentUser().getUsername() + "  于  " + DateUtil.getNowDayString() + "  完成了编号为：  " + map.get("orderBill_id") + "  收货单的收货处理，请及时确认。";
        }
        log.info("OrderController中updateDispatch添加收货单接口返回数据" + result);
        if (result) {
            String orderNo = String.valueOf(map.get("orderBill_id"));
            messageBean.setMessage_url("/order/billPage.page?type=consignee&orderNo=" + map.get("orderBill_id") + "&customStat=1008");
            messageBean.setMessage_creater(SpringSecurityUtils.getCurrentUser().getId().toString());
            messageBean.setMessage_no(orderNo);
            messageBean.setMessage_body(messageBody);
            messageBean.setMessage_status("99");
            messageService.send(messageBean);
            return JsonData.success();
        } else {
            log.error("OrderController中updateDispatch方法异常，接口返回数据" + result);
            return JsonData.fail();
        }
    }

    /**
     * 撤回收货单
     *
     * @param orderBill_id
     * @param surface_id
     * @return
     */
    @RequestMapping(value = "/revokeConsignee.json", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public ResponseData revokeConsignee(String orderBill_id, String surface_id) {
        //删除收获单
        Map consignee = new HashMap();
        consignee.put("orderBill_id", orderBill_id);
        consignee.put("surface_id", surface_id);
        return OrderIOC.delOrderBean(StringUtil.ObjectToJson(consignee));
    }

    /**
     * 撤回收货单
     *
     * @param orderBill_id
     * @param
     * @return
     */
    @RequestMapping(value = "/editConsignee.page")
    public ModelAndView editConsigneePage(String orderBill_id) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("orderBill_id", orderBill_id);
        mv.setViewName("/consignee/editDispatch");
        return mv;
    }

    /**
     * 撤回收货单
     *
     * @param formData
     * @param
     * @return
     */
    @RequestMapping(value = "/editConsignee.json", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public JsonData editConsigneeJson(String formData) {
        Map map = StringUtil.JsonToMap(formData);
        map.put("orderBill_flow", "20");
        ResponseData responseData = OrderIOC.delOrderBean(StringUtil.ObjectToJson(map));
        if (responseData.isRet()) {
            try {
                com.ordercore.Bean.OrderBean orderBean = OrderIOC.baseAnalysisBill(StringUtil.ObjectToJson(map));
                return JsonData.success();
            } catch (Exception e) {
                return JsonData.fail();
            }
        } else {
            return JsonData.fail();
        }
    }

    /**
     * 收款列表界面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/gathering.page", method = RequestMethod.GET)
    public ModelAndView gatheringPage() throws Exception {
        ModelAndView mv = new ModelAndView();
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        if ("99".equals(userDetail.getCompany_type())) {
            mv.setViewName("/shopping/adminGathering");
        } else {
            mv.addObject("consigneeId", userDetail.getCompany_id());
            mv.setViewName("/shopping/gathering");
        }
        return mv;
    }

    /**
     * 确认收款列表数据
     *
     * @param orderNo
     * @param userName
     * @param startTime
     * @param endTime
     * @param payStat
     * @param page
     * @param limit
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/gathering.json", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public JsonData gatheringJson(String consigneeId, String orderNo, String userName, String startTime, String endTime,
                                  String payStat, String page, String limit) throws Exception {
        if (StringUtils.isBlank(page)) {
            page = StaticUtil.pageIndex;
        }
        if (StringUtils.isBlank(limit)) {
            limit = StaticUtil.sizeCount;
        }
        StringBuffer buffer = new StringBuffer();
        // 根据用户名模糊搜索，因为接口需要用户id所以在此处根据用户名模糊查询出用户的id
        if (StringUtils.isNotBlank(userName)) {
            List<UserBean> userList = userService.findAllUserByUserName(userName);
            for (int i = 0; i < userList.size(); i++) {
                UserBean bean = userList.get(i);
                buffer.append(bean.getId());
                if (i < userList.size() - 1) {
                    buffer.append(",");
                }
            }
        }
        // 转成熊能解析的json格式
        Map map = new HashMap();
        map.put("page", page);
        map.put("limit", limit);
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        map.put("payStat", payStat);
        if (StringUtils.isBlank(buffer) && StringUtils.isNotBlank(userName)) {
            map.put("user_id", "不存在");
        } else {
            map.put("user_id", buffer);
        }
        map.put("order_id", orderNo);
        map.put("userGroup_id", consigneeId);
        List<Map> list = null;
        int count = 0;
        ResponseData responseData = OrderIOC.paymentBillList(StringUtil.ObjectToJson(map));
        if (responseData.isRet()) {
            String str = StringUtil.ObjectToJson(responseData.getData());
            list = StringUtil.JsonToList(str);
            for (Map resultMap : list) {
                UserBean bean = userService.findById(Integer.valueOf(resultMap.get("user_id").toString())).get();
                resultMap.put("user_name", bean.getUser_name());
            }
            count = Integer.valueOf(responseData.getCount());
        } else {
            return JsonData.fail("收款列表请求失败，请稍后重试");
        }
        Map resultMap = new HashMap();
        resultMap.put("list", list);
        resultMap.put("total", count == 0 ? 1 : count);
        resultMap.put("orderNo", orderNo);
        resultMap.put("userName", userName);
        resultMap.put("startTime", startTime);
        resultMap.put("endTime", endTime);
        resultMap.put("payStat", payStat);
        resultMap.put("size", limit);
        resultMap.put("page", page);
        return JsonData.success(resultMap);
    }

    /**
     * 付款凭据详情
     *
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/gatheringDetail.json", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public JsonData gatheringDetailJson(String id) throws Exception {
        // 转成熊能解析的json格式
        Map map = new HashMap();
        map.put("payment_pk", id);
        ResponseData responseData = OrderIOC.paymentBillDetail(StringUtil.ObjectToJson(map));
        if (responseData.isRet()) {
            return JsonData.success(responseData.getData());
        } else {
            return JsonData.fail("获取付款凭据详情失败，请稍后重试！");
        }
    }

    /**
     * 确认付款
     *
     * @param id
     * @param orderBill_id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/affirmGatheringPrice.json", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public JsonData AffirmGatheringPriceJson(String id, String orderBill_id) throws Exception {
        // 转成熊能解析的json格式
        Map map = new HashMap();
        map.put("payment_pk", id);
        map.put("payStat", "02");
        map.put("orderBill_id", orderBill_id);
        ResponseData responseData = OrderIOC.paymentBillUpdateByJson(StringUtil.ObjectToJson(map));
        if (responseData.isRet()) {
            return JsonData.success(responseData.getData());
        } else {
            return JsonData.fail("确认付款失败，请稍后重试！");
        }
    }

    /**
     * 新增合同订单
     */
    @RequestMapping(value = "/addOrder.page")
    public ModelAndView addOrderPage(String admin) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("NSLUrl", StaticUtil.SKUIP);
        mv.addObject("url", StaticUtil.SKUIP);
        mv.addObject("admin", admin);
        String companyId = SpringSecurityUtils.getCurrentUser().getCompany_id();
        if (companyId.equals("1")) {
            mv.addObject("success", "success");
        } else {
            mv.addObject("success", "fail");
        }

        mv.addObject("group_id", StaticUtil.GONGYINGLIANGROUP);
        mv.setViewName("/shopping/addOrder");
        return mv;
    }

//    /**
//     * 根据分类ID获取类型为实时的合同SKU列表
//     */
//    @RequestMapping(value = "/getRealTimeSkuListByTreeId.json")
//    public JsonData getRealTimeSkuListByTreeId(String treeId, String contractId, String limit, String page, String key) throws Exception {
//        Map mapData = new HashMap();
//        if (StringUtils.isBlank(treeId)) {
//            List<ContractRealTimePriceBean> contractRealTimePriceBeans = contractRealTimePriceService.getSkuBySkuCodeSetAndContractIdDetail(null, contractId, limit, page, key);
//            mapData.put("list", contractRealTimePriceBeans);
//            mapData.put("count", contractRealTimePriceService.getCountByContractId(contractId, key));
//            return JsonData.success(mapData);
//        }
//        String url = StaticUtil.SKUIP + "/api/getSKUListByCfgCataLogId.json/?id=" + treeId + "&limit=" + limit + "&page=" + page;
//        String result = HttpUtil.getDemo(url);
//        log.info("获取sku详情信息：" + result);
//        Map resultMap = StringUtil.JsonToMap(result);
//        if (resultMap.get("ret").equals(true)) {
//            String aaa = StringUtil.ObjectToJson(resultMap.get("data"));
//            List<Map> listData = StringUtil.JsonToList(aaa);
//            if (listData.size() > 0) {
//                StringBuffer buffer = new StringBuffer();
//                for (Map map : listData) {
//                    buffer.append(map.get("sku_code")).append(",");
//                }
//                String value = buffer.substring(0, buffer.length() - 1);
//                List<ContractRealTimePriceBean> contractRealTimePriceBeans = contractRealTimePriceService.getSkuBySkuCodeSetAndContractIdDetail(value, contractId.toString(), limit, page, null);
//
//                String aa = StringUtil.ObjectToJson(contractRealTimePriceBeans);
//                List<Map> list = StringUtil.JsonToList(aa);
//                mapData.put("list", list);
//                mapData.put("count", resultMap.get("count").toString());
//                return JsonData.success(mapData);
//            } else {
//                List<ContractRealTimePriceBean> contractRealTimePriceBeans = contractRealTimePriceService.getSkuBySkuCodeSetAndContractIdDetail(null, contractId.toString(), limit, page, key);
//                mapData.put("list", contractRealTimePriceBeans);
//                mapData.put("count", contractRealTimePriceBeans.size());
//                return JsonData.success(mapData);
//            }
//
//        } else {
//            return JsonData.fail("获取分类列表失败");
//        }
//    }

    @RequestMapping(value = "/addOrder.json", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public JsonData addOrder(String company_id, String buyer, String consignee_information, String consignee_address, String remark, String order_name, String context, String sku_sum_price, String user_id, String project_name) throws Exception {
        AddreessBean addreessBean = new AddreessBean();
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        Optional<CompanyBean> optional = companyService.findById(Integer.valueOf(company_id));
        addreessBean.setType("analog");
        addreessBean.setOrder_source("EOS");
        addreessBean.setPrice(sku_sum_price);
        addreessBean.setOrder_name(order_name);
        addreessBean.setBuyer(buyer);
        if (StringUtils.isBlank(buyer)) {
            addreessBean.setBuyer("");
        } else {
            addreessBean.setBuyer(buyer);
        }
        if (StringUtils.isBlank(consignee_information)) {
            addreessBean.setConsignee_information("");
        } else {
            addreessBean.setConsignee_information(consignee_information);
        }
        if (StringUtils.isBlank(consignee_address)) {
            addreessBean.setConsignee_address("");
        } else {
            addreessBean.setConsignee_address(consignee_address);
        }
        if (StringUtils.isBlank(remark)) {
            addreessBean.setRemark("");
        } else {
            addreessBean.setRemark(remark);
        }
        if (StringUtils.isBlank(context)) {
            addreessBean.setContext("");
        } else {
            addreessBean.setContext(context);
        }
        addreessBean.setConsignee_name(userDetail.getUsername());
        addreessBean.setPartyA_id("1");
        addreessBean.setProject_name(project_name);
        addreessBean.setUser_id(Integer.valueOf(user_id));
        addreessBean.setPartyA_name(StaticUtil.company);
        addreessBean.setCrtTime(DateUtil.getNowTime("yyyy-MM-dd"));
        addreessBean.setUserGroup_id(optional.get().getId());
        addreessBean.setUserGroup_name(optional.get().getCompany_name());
        String num = sequenceService.getSequenceNum("order");
        String orderBillId = "EOS-" + DateUtil.getNowTime("yyyyMMdd") + "-" + StringUtil.getCode(num, 5);
        addreessBean.setOrderBill_id(orderBillId);
        addreessBean.setId(0);// 默认0，方便熊数据解析，没有实际用途
        addreessBean.setDiscount("0");// 优惠金额默认为0
        addreessBean.setTransport_price("0");// 运费默认为0
        String param = StringUtil.ObjectToJson(addreessBean);
        try {
            com.ordercore.Bean.OrderBean orderBean = OrderIOC.baseAnalysisBill(param);
            //如果是品宅下单，则直接改为付款中状态
            if ("1".equals(userDetail.getCompany_id())) {
                Map map = new HashMap();
                map.put("orderBill_id", orderBean.getOrderBill_id());
                map.put("orderBean_pk", orderBean.getOrderBean_pk());
                map.put("orderBill_flow", "25");
                map.put("orderBill_customStat", "1002");
                String param1 = StringUtil.ObjectToJson(map);
                try {
                    com.ordercore.Bean.OrderBean orderBean1 = OrderIOC.updateOrder(param1);
                    Map map1 = new HashMap<>();
                    map1.put("order_id", orderBean.getOrderBill_id());
                    map1.put("orderBean_pk", orderBean.getOrderBean_pk());
                    map1.put("type", "25");
                    Map result = OrderIOC.queryDeteilById(StringUtil.ObjectToJson(map1));
                    messageService.rabbitMq("kingDeeOrderChange", "kingDeeOrderKey", StringUtil.ObjectToJson(result));
                    return JsonData.success();
                } catch (Exception e) {
                    return JsonData.fail();
                }
            } else {
                String message_body = addreessBean.getUserGroup_name() + "  " + userDetail.getUsername() + "  于  " + DateUtil.getNowDayString() + "  下了一笔采购订单，编号为：  " + orderBillId + "  请确认清单。";
                String message_creater = addreessBean.getUser_id().toString();
                orderCreateMessage(message_body, message_creater, orderBillId, String.valueOf(orderBean.getOrderBean_pk()));
            }
            return JsonData.success();
        } catch (Exception e) {
            return JsonData.fail("下单失败，请重试！");
        }
    }


    /**
     * 订单新建成功消息推送
     */
    public void orderCreateMessage(String message_body, String message_creater, String orderBillId, String orderBean_pk) throws Exception {
        List<UserBean> userList = userService.findAllUserByGroupId(StaticUtil.GONGYINGLIANGROUP);
        StringBuffer buffer = new StringBuffer();
        for (UserBean userBean : userList) {
            buffer.append(userBean.getId()).append(",");
        }
        MessageBean messageBean = new MessageBean();
        messageBean.setMessage_url("/order/orderDetail.page?orderNo=" + orderBillId + "&orderBean_pk=" + orderBean_pk);
        messageBean.setMessage_no(orderBillId);
        messageBean.setMessage_type("msg001");
        messageBean.setMessage_body(message_body);
        messageBean.setMessage_creater(message_creater);
        messageBean.setMessage_sendee(buffer.toString());
        messageBean.setMessage_status("99");
        messageService.send(messageBean);
    }

    /**
     * 导出订单明细
     *
     * @param response
     * @param orderNo
     * @param orderBean_pk
     * @throws IOException
     * @throws Exception
     */
    @RequestMapping(value = "/export.json")
    public void ExportExcel(HttpServletResponse response, String orderNo, String orderBean_pk) throws IOException, Exception {
        Map map = new HashMap();
        map.put("order_id", orderNo);
        map.put("orderBean_pk", orderBean_pk);
        map.put("type", "25");
        String param = StringUtil.ObjectToJson(map);
        try {
            Map<String, Object> result = OrderIOC.queryDeteilById(param);
            List<Map> list = StringUtil.JsonToList(StringUtil.ObjectToJson(result.get("context")));
            // 第一步，创建一个webbook，对应一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet("订单明细");
            //列宽
            sheet.setColumnWidth(0, 60 * 100);
            sheet.setColumnWidth(1, 160 * 100);
            sheet.setColumnWidth(2, 30 * 100);
            sheet.setColumnWidth(3, 30 * 100);
            sheet.setColumnWidth(4, 60 * 100);
            sheet.setColumnWidth(5, 60 * 100);
            sheet.setColumnWidth(6, 100 * 100);
            sheet.setColumnWidth(7, 40 * 100);
            sheet.setColumnWidth(8, 40 * 100);
            sheet.setColumnWidth(9, 100 * 100);
            // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFCellStyle headstyle = wb.createCellStyle();
            headstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
            headstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
            headstyle.setLocked(true);
            headstyle.setWrapText(true);// 自动换行
            HSSFRow row0 = sheet.createRow((int) 0);
            row0.setHeight((short) 900);
            HSSFCell cell0 = row0.createCell(0);
            cell0.setCellValue(new HSSFRichTextString(result.get("userGroup_name") + "  订单明细"));
            cell0.setCellStyle(headstyle);
            /**
             * 合并单元格
             *    第一个参数：第一个单元格的行数（从0开始）
             *    第二个参数：第二个单元格的行数（从0开始）
             *    第三个参数：第一个单元格的列数（从0开始）
             *    第四个参数：第二个单元格的列数（从0开始）
             */
            CellRangeAddress range = new CellRangeAddress(0, 0, 0, 9);
            sheet.addMergedRegion(range);
            HSSFRow row1 = sheet.createRow((int) 1);
            row1.setHeight((short) 400);
            CellRangeAddress range1 = new CellRangeAddress(1, 1, 0, 9);
            sheet.addMergedRegion(range1);
            HSSFCell cell1 = row1.createCell(1);
            cell1.setCellValue(new HSSFRichTextString("订单编号：" + result.get("orderBill_id") + "   创建时间：" + result.get("crtTime") + "   订单总额：" + result.get("price") + "   供应链联系人：" + result.get("buyer") + "   客户名称：" + result.get("userGroup_name") + "   备注：" + result.get("remark")));
            cell1.setCellStyle(headstyle);
            HSSFRow row = sheet.createRow((int) 2);
//            HSSFCell cell1 = row1.createCell(0);
            // 第四步，创建单元格，并设置值表头 设置表头居中
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("材料编码");
            cell.setCellStyle(style);
            cell = row.createCell(1);
            cell.setCellValue("材料名称");
            cell.setCellStyle(style);
            cell = row.createCell(2);
            cell.setCellValue("单位");
            cell.setCellStyle(style);
            cell = row.createCell(3);
            cell.setCellValue("品牌");
            cell.setCellStyle(style);
            cell = row.createCell(4);
            cell.setCellValue("型号");
            cell.setCellStyle(style);
            cell = row.createCell(5);
            cell.setCellValue("规格参数");
            cell.setCellStyle(style);
            cell = row.createCell(6);
            cell.setCellValue("到货时间");
            cell.setCellStyle(style);
            cell = row.createCell(7);
            cell.setCellValue("价格");
            cell.setCellStyle(style);
            cell = row.createCell(8);
            cell.setCellValue("数量");
            cell.setCellStyle(style);
            cell = row.createCell(9);
            cell.setCellValue("备注");
            cell.setCellStyle(style);
            // 第五步，写入实体数据 实际应用中这些数据从数据库得到，

            for (int i = 0; i < list.size(); i++) {
                row = sheet.createRow((int) 2 + 1 + i);

                // 第四步，创建单元格，并设置值
                row.createCell(0).setCellValue(list.get(i).get("sku_code") == null ? "" : list.get(i).get("sku_code").toString());
                row.createCell(1).setCellValue(list.get(i).get("sku_name") == null ? "" : list.get(i).get("sku_name").toString());
                row.createCell(2).setCellValue(list.get(i).get("sku_unit") == null ? "" : list.get(i).get("sku_unit").toString());
                row.createCell(3).setCellValue(list.get(i).get("sku_brand") == null ? "" : list.get(i).get("sku_brand").toString());
                row.createCell(4).setCellValue(list.get(i).get("sku_model") == null ? "" : list.get(i).get("sku_model").toString());
                row.createCell(5).setCellValue(list.get(i).get("sku_slug_set") == null ? "" : list.get(i).get("sku_slug_set").toString());
                row.createCell(6).setCellValue(list.get(i).get("arriveTime") == null ? "" : list.get(i).get("arriveTime").toString());
                row.createCell(7).setCellValue(list.get(i).get("sku_contract_price") == null ? "" : list.get(i).get("sku_contract_price").toString());
                row.createCell(8).setCellValue(list.get(i).get("purNum") == null ? "" : list.get(i).get("purNum").toString());
                row.createCell(9).setCellValue(list.get(i).get("sku_remark") == null ? "" : list.get(i).get("sku_remark").toString());
            }

            // 第六步，将文件存到指定位置
            try {
                String filename = result.get("orderBill_id").toString() + "订单明细";
                String fileName = new String(filename.getBytes(), "iso8859-1") + ".xls";
                response.setContentType("application/octet-stream");
                response.setHeader("Content-disposition", "attachment;filename=" + fileName);//默认Excel名称
                response.flushBuffer();
                response.setCharacterEncoding("UTF-8");
                wb.write(response.getOutputStream());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                wb.close();
            }
        } catch (Exception e) {

        }
//        String result = HttpUtil.post(StaticUtil.ORDERDETAIL, param);
//        Map orderMap = StringUtil.JsonToMap(result);

//        if (StringUtil.getBoolean(String.valueOf(orderMap.get("ret")))) {
//            Map order = StringUtil.JsonToMap(StringUtil.ObjectToJson(orderMap.get("data")));
//            List<Map> list = StringUtil.JsonToList(StringUtil.ObjectToJson(order.get("context")));

//        } else {
//
//        }
    }

    /**
     * 订单明细打印
     */
    @RequestMapping(value = "/printOrder.page", method = RequestMethod.GET)
    public ModelAndView printOrder(String orderNo, String orderBean_pk) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("orderNo", orderNo);
        mv.addObject("orderBean_pk", orderBean_pk);
        mv.setViewName("/shopping/printOrder");
        return mv;
    }

    private String userIdToUserName(String userIdList) throws Exception {
        if ("null".equals(userIdList)) {
            return "";
        } else {
            userIdList = userIdList.substring(1, userIdList.length() - 1);
            if (StringUtils.isNotBlank(userIdList)) {
                String[] userId = userIdList.split(",");
                StringBuffer buffer = new StringBuffer();
                for (int j = 0; j < userId.length; j++) {
                    UserBean userBean = userService.findUserDetail(userId[j]);
                    buffer.append(userBean.getUser_name()).append(",");
                }
                return buffer.toString();
            } else {
                return "";
            }
        }

    }


}
